package cn.muqingfeng.bbs.ui;

import java.io.File;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.util.EntityUtils;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.net.http.AndroidHttpClient;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import cn.muqingfeng.api.RequestHelper;
import cn.muqingfeng.api.UriHelper;
import cn.muqingfeng.api.to.BaseResponseTO;
import cn.muqingfeng.api.to.UserTO;
import cn.muqingfeng.bbs.R;
import cn.muqingfeng.bbs.constants.Constants;
import cn.muqingfeng.bbs.ui.widget.AvatarPickerPopup;
import cn.muqingfeng.util.AccountManager;
import cn.muqingfeng.util.BitmapBinder;

import com.android.volley.toolbox.NetworkImageView;
import com.google.gson.Gson;

public class AccountActivity extends BaseActivity implements OnClickListener {
	private static Object LOCK = new Object();
	private static final int REQUEST_CODE_CHANGEPASS = 100;
	private AvatarPickerPopup avatarPickerPopup;
	private UserTO mUserTO;
	private TextView mUsernameView;
	private boolean isUploading = false;
	private NetworkImageView mAvatarView;
	private ProgressDialog mDialog;
	private HttpPost mUploadRequest;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.account_manage);
		setupViews();
	}

	private void setupViews() {
		findViewById(R.id.back).setOnClickListener(this);
		findViewById(R.id.avatar_layout).setOnClickListener(this);
		findViewById(R.id.change_pwd_layout).setOnClickListener(this);
		findViewById(R.id.logout).setOnClickListener(this);
		mUserTO = AccountManager.getUser(getApplicationContext());
		mUsernameView = (TextView) findViewById(R.id.username);
		mUsernameView.setText(mUserTO.getUsername());
		mAvatarView = (NetworkImageView) findViewById(R.id.avatar);
		bindAvatar();
	}

	private void bindAvatar() {
		String avatarUrl = UriHelper.getAvatarUrl(mUserTO.getUid());
		BitmapBinder.bindNetImage(getApplicationContext(), mAvatarView, avatarUrl,
				R.drawable.ic_default_avatar);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.back:
			finish();
			break;
		case R.id.avatar_layout:
			avatarPickerPopup = new AvatarPickerPopup(this);
			ViewGroup decor = (ViewGroup) getWindow().getDecorView();
			avatarPickerPopup.showAtLocation(decor, Gravity.BOTTOM, 0, 0);
			break;
		case R.id.change_pwd_layout: {
			Intent intent = new Intent(this, ChangePassActivity.class);
			startActivityForResult(intent, REQUEST_CODE_CHANGEPASS);
		}
			break;
		case R.id.logout:
			AccountManager.clear(getApplicationContext());
			finish();
			break;
		default:
			break;
		}
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode != RESULT_OK) {
			return;
		}
		// 根据上面发送过去的请求码来区别
		switch (requestCode) {
		case REQUEST_CODE_CHANGEPASS:
			finish();
			break;
		case Constants.REQUEST_CODE_PICK_PHOTO:
		case Constants.REQUEST_CODE_TAKE_PHOTO:
			final String path = data.getStringExtra("CropperPhotoPath");
			changeAvatar(path);
			break;
		default:
			break;
		}
	}

	private void changeAvatar(final String path) {
		synchronized (LOCK) {
			if (isUploading)
				return;
			isUploading = true;
			new AsyncTask<Void, Void, BaseResponseTO>() {

				protected void onPreExecute() {
					showDialog();
				};

				@Override
				protected BaseResponseTO doInBackground(Void... params) {
					try {
						String requestUrl = UriHelper.getChangeAvatarUrl();
						AndroidHttpClient httpclient = AndroidHttpClient.newInstance(RequestHelper.UA,
								getApplicationContext());
						try {
							mUploadRequest = new HttpPost(requestUrl);

							FileBody bin = new FileBody(new File(path));

							MultipartEntity reqEntity = new MultipartEntity();
							reqEntity.addPart("Filedata", bin);
							UserTO user = AccountManager.getUser(getApplicationContext());
							mUploadRequest.addHeader(UriHelper.PARAMS_HEADER_USERNAME, user.getUsername());
							mUploadRequest.addHeader(UriHelper.PARAMS_HEADER_PASSWORD,
									AccountManager.getPassword(getApplicationContext()));
							mUploadRequest.setEntity(reqEntity);

							HttpResponse response = httpclient.execute(mUploadRequest);
							HttpEntity resEntity = response.getEntity();
							String result = EntityUtils.toString(resEntity);
							if (!TextUtils.isEmpty(result)) {
								Gson gson = new Gson();
								return gson.fromJson(result, BaseResponseTO.class);
							}
						} finally {
							httpclient.close();
							mUploadRequest = null;
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
					return null;
				}
				
				protected void onPostExecute(BaseResponseTO result) {
					if (!isDestroied()) {
						dismissDialog();
						if (result == null) {
							Toast.makeText(getApplicationContext(), "修改失败！",
									Toast.LENGTH_SHORT).show();
						} else {
							if (result.isSuccess()) {
								Toast.makeText(getApplicationContext(), "修改成功！",
										Toast.LENGTH_SHORT).show();
								mAvatarView.clearCache();
								bindAvatar();
							} else {
								String msg = result.getMessage();
								msg = TextUtils.isEmpty(msg) ? "修改失败" : msg;
								Toast.makeText(getApplicationContext(), msg,
										Toast.LENGTH_SHORT).show();
							}
						}
					}
				}
			}.execute();
		}
	}

	private void showDialog() {
		if (mDialog != null && mDialog.isShowing()) {
			return;
		}
		mDialog = new ProgressDialog(this);
		mDialog.setOnDismissListener(new OnDismissListener() {

			@Override
			public void onDismiss(DialogInterface dialog) {
				isUploading = false;
				if (mUploadRequest != null) {
					mUploadRequest.abort();
				}
			}
		});
		mDialog.setMessage("正在请求，请稍等...");
		mDialog.show();
	}

	private void dismissDialog() {
		if (mDialog != null && mDialog.isShowing()) {
			mDialog.dismiss();
		}
	}
}
